package cn.virens.web.components.open.wxma.config;

import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;

/**
 * 微信配置信息公共类
 * 
 * @author virens
 */
public abstract class AbstractWxMaCacheConfig extends WxMaDefaultConfigImpl {
	private static final String CARD_API_TICKET = "cardApiTicket";
	private static final String ACCESS_TOKEN = "accessToken";
	private static final String JSAPI_TICKET = "jsapiTicket";

	@Override
	public String getAccessToken() {
		return get(key(ACCESS_TOKEN));
	}

	@Override
	public void expireAccessToken() {
		this.rm(key(ACCESS_TOKEN));
	}

	@Override
	public boolean isAccessTokenExpired() {
		return ttl(key(ACCESS_TOKEN)) < 2;
	}

	@Override
	public synchronized void updateAccessToken(String accessToken, int expiresInSeconds) {
		this.set(key(ACCESS_TOKEN), accessToken, expiresInSeconds - 200);
	}

	@Override
	public String getJsapiTicket() {
		return get(key(JSAPI_TICKET));
	}

	@Override
	public void expireJsapiTicket() {
		this.rm(key(JSAPI_TICKET));
	}

	@Override
	public boolean isJsapiTicketExpired() {
		return ttl(key(JSAPI_TICKET)) < 2;
	}

	@Override
	public void updateJsapiTicket(String jsapiTicket, int expiresInSeconds) {
		this.set(key(JSAPI_TICKET), jsapiTicket, expiresInSeconds - 200);
	}

	@Override
	public String getCardApiTicket() {
		return get(key(CARD_API_TICKET));
	}

	@Override
	public void expireCardApiTicket() {
		this.rm(key(CARD_API_TICKET));
	}

	@Override
	public boolean isCardApiTicketExpired() {
		return ttl(key(CARD_API_TICKET)) < 2;
	}

	@Override
	public void updateCardApiTicket(String cardApiTicket, int expiresInSeconds) {
		this.set(key(CARD_API_TICKET), cardApiTicket, expiresInSeconds - 200);
	}

	/** 获取缓存对应的TTL值 */
	protected abstract int ttl(String key);

	/** 删除对应的缓存值 */
	protected abstract void rm(String key);

	/** 获取缓存对应的值 */
	protected abstract String get(String key);

	/** 将属性存入缓存 */
	protected abstract void set(String key, String value, int ttl);

	private String key(String key) {
		return String.format("weixin:ma:config:%s:%s", getAppid(), key);
	}

}
